<template>
  <div>
    <el-card style="margin: 20px 0">
      <CategorySelect
        :show="!isShowTable"
        @getCategoryId="getCategoryId"
      ></CategorySelect>
    </el-card>
    <el-card>
      <div v-show="isShowTable">
        <el-button
          type="primary"
          icon="el-icon-plus"
          :disabled="!category3Id"
          @click="addAttr"
        >
          添加属性
        </el-button>
        <el-table :data="attrList" style="width: 100%" border stripe>
          <el-table-column type="index" label="序号" width="80px">
          </el-table-column>
          <el-table-column prop="attrName" label="属性名称" width="150">
          </el-table-column>
          <el-table-column label="属性值列表" width="width">
            <template slot-scope="{ row }">
              <el-tag
                v-for="item in row.attrValueList"
                :key="item.id"
                type="success"
                style="margin-right: 8px"
                >{{ item.valueName }}</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150px">
            <template #default="{ row }">
              <el-button
                type="warning"
                icon="el-icon-edit"
                size="mini"
                @click="updateAttr(row)"
              ></el-button>
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 添加或修改属性的解构 -->
      <div v-show="!isShowTable">
        <el-form ref="formRef" label-width="80px" :model="attrInfo">
          <el-form-item label="属性名" style="width: 300px">
            <el-input
              v-model="attrInfo.attrName"
              placeholder="请输入属性名"
            ></el-input>
          </el-form-item>
        </el-form>
        <el-button
          type="primary"
          icon="el-icon-plus"
          :disabled="!attrInfo.attrName"
          @click="addAttrValue"
        >
          添加属性值
        </el-button>
        <el-button type="info" @click="isShowTable = true">取消</el-button>
        <el-table
          :data="attrInfo.attrValueList"
          style="width: 100%; margin: 20px 0"
          border
          stripe
        >
          <el-table-column
            type="index"
            label="序号"
            align="center"
            width="100px"
          >
          </el-table-column>
          <el-table-column prop="prop" label="属性值名称" width="width">
            <template #default="{ row, $index }">
              <!-- input和span进行来回切换 -->
              <el-input
                v-if="row.flag"
                :ref="$index"
                v-model="row.valueName"
                placeholder="请输入属性值名称"
                size="mini"
                @blur="toLook(row)"
                @keyup.native.enter="toLook(row)"
              ></el-input>
              <span
                v-else
                style="display: block"
                @click="toEdit(row, $index)"
                >{{ row.valueName }}</span
              >
            </template>
          </el-table-column>
          <el-table-column label="操作" width="width">
            <template #default="{ row }">
              <el-popconfirm
                :title="`确定删除${row.valueName}?`"
                @onConfirm="deleteAttrValue($index)"
              >
                <el-button
                  slot="reference"
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                ></el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <el-button
          type="primary"
          :disabled="attrInfo.attrValueList.length < 1"
          @click="saveAttr"
          >保存</el-button
        >
        <el-button @click="isShowTable = true">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import { getAttrListApi, saveAttrInfoApi } from '@/api/attr'

export default {
  name: 'Attr',
  data () {
    return {
      category1Id: '',
      category2Id: '',
      category3Id: '',
      // 平台属性数组
      attrList: [],
      isShowTable: true,
      // 收集新增或修改的属性值
      attrInfo: {
        attrName: '', // 属性名
        attrValueList: [ // 属性值 因为属性可以是多个,所以需要的是数组
          // {
          //   attrId: 0, // 相应属性名的Id
          //   valueName: '' // 相应属性值名称
          // }
        ],
        categoryId: 0, // 三级分类的id
        categoryLevel: 3 // 服务器需要区分是几级Id
      }
    }
  },
  methods: {
    getCategoryId ({ categoryId, level }) {
      // console.log(categoryId, level)
      if (level === 1) {
        this.category1Id = categoryId
        this.category2Id = ''
        this.category3Id = ''
      } else if (level === 2) {
        this.category2Id = categoryId
        this.category3Id = ''
      } else {
        this.category3Id = categoryId
        this.getAttrList()
      }
    },
    async getAttrList () {
      try {
        const { data } = await getAttrListApi({ category1Id: this.category1Id, category2Id: this.category2Id, category3Id: this.category3Id })
        // console.log(data)
        this.attrList = data
      } catch (error) {
        console.log(error)
      }
    },
    addAttrValue () {
      // 向属性值数组中添加元素
      this.attrInfo.attrValueList.push({
        attrId: this.attrInfo.id, // 相应属性的Id
        valueName: '', // 相应属性值的名称
        flag: true
      })
      this.$nextTick(() => {
        this.$refs[this.attrInfo.attrValueList.length - 1].focus()
      })
    },
    addAttr () {
      this.isShowTable = false
      this.attrInfo = {
        attrName: '', // 属性名
        attrValueList: [ // 属性值 因为属性可以是多个,所以需要的是数组
          // {
          //   attrId: 0, // 相应属性名的Id
          //   valueName: '' // 相应属性值名称
          // }
        ],
        categoryId: this.category3Id, // 三级分类的id
        categoryLevel: 3 // 服务器需要区分是几级Id
      }
    },
    updateAttr (row) {
      // console.log(row)
      this.isShowTable = false
      // 用浅拷贝无法实现,因为出现了数组和对象,需要使用深拷贝
      // this.attrInfo = { ...row }
      this.attrInfo = JSON.parse(JSON.stringify(row))
      // 在修改某一个属性的时候,将相应的属性值元素上添加flag标记
      this.attrInfo.attrValueList.forEach(item => {
        // 这种方式添加的flag字段不是响应式的
        // item.flag = false
        // 第一个参数是对象,第二个是属性,第三个是属性值
        this.$set(item, 'flag', false)
      })
    },
    toLook (row) {
      // 如果用户输入为空则需要提示用户输入
      if (row.valueName.trim() === '') {
        this.$message.info('请输入正常属性值')
        return
      }
      // 输入内容和不能重复
      const isRepeat = this.attrInfo.attrValueList.some(item => {
        if (row !== item) {
          return row.valueName === item.valueName
        }
      })
      if (isRepeat) return
      row.flag = false
    },
    toEdit (row, index) {
      // console.log(row, index)
      row.flag = true
      // 获取input节点,实现自动聚焦
      this.$nextTick(() => {
        this.$refs[index].focus()
      })
    },
    deleteAttrValue (index) {
      // 最新版本的element-ui为@confirm
      // console.log(123)
      this.attrInfo.attrValueList.splice(index, 1)
    },
    async saveAttr () {
      this.attrInfo.attrValueList = this.attrInfo.attrValueList.filter(item => {
        if (item.valueName !== '') {
          delete item.flag
          return true
        }
      })
      try {
        const data = await saveAttrInfoApi(this.attrInfo)
        console.log(data)
        this.$message.success('保存成功')
        this.getAttrList()
        this.isShowTable = true
      } catch (error) {
        // console.log(error)
        this.$message.error('保存失败')
      }
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
